﻿using System;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Phone.Shell;
using WaitLess.App.Converters;
using WaitLess.App.Services.Interfaces;
using WaitLess.App.ViewModels;

namespace WaitLess.App.Views
{
    public partial class DetailsPage : PhoneApplicationPageBase
    {
        private const string PinButtonText = "pin to start";
        private const string CheckinButtonText = "checkin";

        private readonly INavigationService _navigationService;

        public DetailsViewModel ViewModel
        {
            get
            {
                return DataContext as DetailsViewModel;
            }
        }

        public DetailsPage()
        {
            InitializeComponent();

            DataContext = ContainerInitializer.Get<DetailsViewModel>();
            _navigationService = ContainerInitializer.Get<INavigationService>();
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            LoadDefaultMunicipalOfficeImage(sender as Image);
        }

        private static void LoadDefaultMunicipalOfficeImage(Image image)
        {
            var defaultImage = new BitmapImage(new Uri(@"/Assets/MunicipalOffices/Default.png", UriKind.Relative));

            image.Source = defaultImage;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var municipalOfficeId = NavigationContext.QueryString["municipalOfficeId"];

            ViewModel.MunicipalOfficeId = municipalOfficeId;
            ViewModel.LoadData();

            LoadApplicationBar();
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);

            RemoveApplicationBarButton(PinButtonText, CheckinButtonText);
        }

        private void LoadApplicationBar()
        {
            AddPinButton();
            AddCheckinButton();
        }

        private bool IsApplicationBarButtonAdded(string text)
        {
            foreach (ApplicationBarIconButton button in ApplicationBar.Buttons)
            {
                if (button.Text == text)
                    return true;
            }

            return false;
        }

        private void RemoveApplicationBarButton(params string[] buttonText)
        {
            for (int i = ApplicationBar.Buttons.Count - 1; i > -1; i--)
            {
                var button = (ApplicationBarIconButton)ApplicationBar.Buttons[i];

                if (buttonText.Contains(button.Text))
                    ApplicationBar.Buttons.Remove(button);
            }
        }

        #region PinButton

        private void AddPinButton()
        {

            if (IsApplicationBarButtonAdded(PinButtonText))
                return;

            var pinButton = new ApplicationBarIconButton()
            {
                Text = PinButtonText,
                IconUri = new Uri("/Assets/ApplicationBar.Pin.png", UriKind.Relative)
            };

            pinButton.Click += pin_Click;

            ApplicationBar.Buttons.Add(pinButton);
        }

        private void pin_Click(object sender, EventArgs e)
        {
            if (!ViewModel.IsDataLoaded)
                return;

            var detailsPageUri = _navigationService.GetDetailsPageUri(ViewModel.MunicipalOfficeId);
            var tileUri = _navigationService.GetFoursquarePageUri(detailsPageUri);
            var isPinned = ShellTile.ActiveTiles.Any(t => Uri.Compare(t.NavigationUri, tileUri, UriComponents.AbsoluteUri, UriFormat.Unescaped, StringComparison.InvariantCultureIgnoreCase) == 0);
            if (isPinned)
                return;

            var tileImage = new MunicipalOfficeToImageConverter().Convert(ViewModel.MunicipalOfficeId, typeof(string), null, Thread.CurrentThread.CurrentUICulture);
            var tileData = new StandardTileData
            {
                Title = ViewModel.Title,
                BackgroundImage = new Uri(tileImage.ToString(), UriKind.Relative)
            };

            ShellTile.Create(tileUri, tileData);
        }

        #endregion

        #region CheckinButton

        private void AddCheckinButton()
        {
            var checkinButtonText = "checkin";
            if (IsApplicationBarButtonAdded(checkinButtonText))
                return;

            var checkInButton = new ApplicationBarIconButton()
            {
                Text = checkinButtonText,
                IconUri = new Uri("/Assets/ApplicationBar.Checkin.Foursquare.png", UriKind.Relative)
            };

            checkInButton.Click += checkInButton_Click;
            ViewModel.PropertyChanged += (s, e) => 
            { 
                if(e.PropertyName == "CanCheckIn") 
                    checkInButton.IsEnabled = ViewModel.CanCheckIn; 
            };

            ApplicationBar.Buttons.Add(checkInButton);
        }

        private void checkInButton_Click(object sender, EventArgs e)
        {
            ViewModel.CheckIn();
        }

        #endregion
    }
}